package paypal

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/bobo-rs/innovideo-services/library/models"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/plutov/paypal/v4"
)

// Notify 回调支付信息
func (p *SPayPal) Notify(ctx context.Context, f func(ctx context.Context, payNo, tradeNo, event string, arg ...interface{}) error) (res *models.PayNotifyResponse, err error) {
	bodyBuff := ghttp.RequestFromCtx(ctx).GetBody()
	defer func() {
		g.Log().Debug(ctx, `PayPal支付回调-WebHook请求`, bodyBuff)
		if err != nil {
			g.Log().Debug(ctx, `PayPal支付回调-WebHook回调事件失败`, err)
		}
	}()

	// 客户端初始化
	client, err := p.Client(ctx)
	if err != nil {
		return nil, fmt.Errorf(`实例客户端失败%w`, err)
	}

	// 回调事件签名认证
	resp, err := client.VerifyWebhookSignature(ctx, ghttp.RequestFromCtx(ctx).Request, p.webHookId)
	if err != nil {
		return nil, err
	}

	// 验证状态
	if resp.VerificationStatus != `SUCCESS` {
		return nil, fmt.Errorf(`PayPal支付失败，Webhook验证失败%s`, resp.VerificationStatus)
	}

	// 回调参数
	var body paypal.AnyEvent
	if err = json.Unmarshal(bodyBuff, &body); err != nil {
		return nil, fmt.Errorf(`PayPal支付失败，解析回调数据失败%w`, err)
	}

	// 初始化
	res = &models.PayNotifyResponse{
		PayNo:       body.ID,
		Description: body.Summary,
		//TradeNo:     body.Resource.MarshalJSON(),
	}
	// 按事件处理回调结果
	switch body.EventType {
	case paypal.EventCheckoutOrderApproved:
		// 订单支付
		res.Scene = `pay`
	case paypal.EventPaymentCaptureRefunded:
		// 订单退款
		res.Scene = `refund`
	default:
		return nil, fmt.Errorf(`PayPal支付失败，未识别到的Event事件[%s]`, body.EventType)
	}
	// 支付成功-回调处理后置逻辑（如：更新订单支付状态，订单退款等）
	err = f(ctx, res.PayNo, res.TradeNo, res.Scene)
	return
}
